package pkj.no.notetab.gui;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.*;

import javax.swing.text.*;


public class TextHolder extends JEditorPane implements KeyListener {

	private ArrayList<String> history = new ArrayList<String>();
	private Tab tab;
	private Tabs tabs;

	private int historyIndex = -1;

	public TextHolder(Tabs tabs, Tab tab) {
		super();
		this.tab = tab;
		this.tabs = tabs;
		addKeyListener(this);

	}

	public void unsave() {
		if (tab.isSaved()) {
			tab.setSaved(false);
			tabs.refresh();
			// Request focus back from tabs to the textholder.
			// We dont want saving to interrupt typing area.
			this.requestFocus();
		}
	}

	@Override
	public void keyPressed(KeyEvent ev) {

		// Go back in history.
		if (ev.isControlDown() && ev.getKeyCode() == KeyEvent.VK_Z) {
			if (history.size() > 0) {
				if (historyIndex == -1)
					historyIndex = history.size();
				System.out.println("BACK HISTORY TO " + historyIndex);
				if (historyIndex > 0)
					setText(history.get(historyIndex--));
				unsave();
			}
		} else if (ev.isControlDown() && ev.getKeyCode() == KeyEvent.VK_Y) {
			if (history.size() > 0) {
				if (historyIndex != -1 && historyIndex < history.size()) {
					setText(history.get(historyIndex++));
					unsave();
				}

			}
		} else if (ev.isControlDown() && ev.getKeyCode() == KeyEvent.VK_S) {
			try {
				tab.save();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			
			
			
			history.add(getText());
			unsave();

			
		}

	}

	@Override
	public void keyReleased(KeyEvent ev) {

	}

	@Override
	public void keyTyped(KeyEvent ev) {
		
	}

}
